var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
	
//定义基准值
var barWidth = 15,step=20,bgStep=2,barHeigh=100,canvasWidth=200,canvasHeight=100;
//开始移动鼠标坐标
var sourcePoint = {x:-1,y:-1};
//待移动块值
var newHeigh = 0;
//开始移动动个体经营者
var sourceArrayIndex={barIndex:-1,dataIndex:-1}
//整条移动数组索引
var changeBarIndex={source:-1,target:-1};

var index, targetIndex = -1;
//单位刻度值
var scaleUnitValue = 20;


//数据结构
var dataSet = [
    {barName:'岗位1',data:[
        {url:'',h:25},
        {url:'',h:15},
        {url:'',h:35},
    ]},
    {barName:'岗位2',data:[
        {url:'',h:15},
        {url:'',h:45},
        {url:'',h:15},
    ]},
    {barName:'岗位3',data:[
        {url:'',h:35},
        {url:'',h:15},
        {url:'',h:35},
    ]},
    {barName:'岗位4',data:[
        {url:'',h:25},
        {url:'',h:25},
        {url:'',h:35},
    ]},
    {barName:'岗位5',data:[
        {url:'',h:15},
        {url:'',h:25},
        {url:'',h:25},
    ]},
]

//根据数据自动画图
autoDraw(dataSet)
	
//注：使用这个函数，需要给Canvas元素的position设为absolute。
/**
 * 要判断事件对象发生的位置，事件对象e的layerX和layerY属性表示Canvas内部坐标系中的坐标
 * */
function getEventPosition(ev){
  var x, y;
  if (ev.layerX || ev.layerX == 0) {
    x = ev.layerX;
    y = ev.layerY;
  } else if (ev.offsetX || ev.offsetX == 0) { // Opera
    x = ev.offsetX;
    y = ev.offsetY;
  }
  return {x: x, y: y};
}

/**
 * 监控鼠标按下动作
*/
 c.onmousedown = function(ev){

    //获取鼠标坐标
    var x, y;
    if (ev.layerX || ev.layerX == 0) {
        x = ev.layerX;
        y = ev.layerY;
    } else if (ev.offsetX || ev.offsetX == 0) { // Opera
        x = ev.offsetX;
        y = ev.offsetY;
    }

    //记录坐标信息
    sourcePoint.x = x;
    sourcePoint.y = y;

    // 获取鼠标选择矩形所在数据索引
    getClickRectIndex(sourcePoint.x,sourcePoint.y);

    timeOutEvent = setTimeout("longPress()",500);
    ev.preventDefault();

    //监听拖拽动作
    drag(x,y);
};
        // //缩放
        // c.onmousewheel = function(ev){
        //     var e = ev||event;
        //     num += e.wheelDelta/1200;
        //     r = 30*num;
        //     ctx.clearRect(0,0,c.width,c.height);
        //     if(ax == null || ay == null){
        //         createBlock(200,200,r);
        //     }else{
        //         if(r>0){
        //             createBlock(ax,ay,r);
        //         }
        //     }
        // };

/**
 * 拖拽处理函数
 * */
function drag(x,y){

    /**
     * 鼠标移动事件
     * */
    c.onmousemove = function(ev){
        var x, y;
        if (ev.layerX || ev.layerX == 0) {
            x = ev.layerX;
            y = ev.layerY;
        } else if (ev.offsetX || ev.offsetX == 0) { // Opera
            x = ev.offsetX;
            y = ev.offsetY;
        }

        console.log("鼠标坐标 = ",x,y)
        clearTimeout(timeOutEvent);
        timeOutEvent = 0;

        if (x > 0 && x < canvasWidth && y > 0 && y < canvasHeight) {
            
            
            // 鼠标移动每一帧都清楚画布内容，然后重新画圆
            ctx.clearRect(0,0,c.width,c.height);
            // autoDraw(dataSet);
            //    drawBar(data,backgroudBar);

            //实时绘制画布
            createBlock(x,y);
        } else {
            console.log('无法操作，超出图表范围！');
        }
    }
    /**
     * 鼠标移开事件
     */
    c.onmouseup = function(){
        c.onmousemove = null;
        c.onmouseup = null;
        clearTimeout(timeOutEvent);
        if(timeOutEvent!=0){
            // alert("这是点击");
            
        
        }else{

            //拖拽处理逻辑

            console.log("changeIndex ",changeBarIndex)
            if(changeBarIndex.target!=-1&&changeBarIndex.source!=-1){

                //整条交换
                if (dataSet[changeBarIndex.source].data && dataSet[changeBarIndex.target].data) {

                    //过滤移动到相同位置
                    if (changeBarIndex.source == changeBarIndex.target) {
                        return;
                    }
                    
                    var source = dataSet[changeBarIndex.source].data;
                    var target = dataSet[changeBarIndex.target].data;
                    var sourceName = dataSet[changeBarIndex.source].barName;
                    var targetName = dataSet[changeBarIndex.target].barName;
                    dataSet[changeBarIndex.source].data=target;
                    dataSet[changeBarIndex.target].data=source;
                    dataSet[changeBarIndex.source].barName=targetName;
                    dataSet[changeBarIndex.target].barName=sourceName;
                }

               

            }else{
                
                 //移动小块
                console.log("sourceArrayIndex   ", sourceArrayIndex);
                if (sourceArrayIndex.barIndex != -1 && sourceArrayIndex.dataIndex != -1) {
                    
                    if (dataSet[sourceArrayIndex.barIndex].data&&dataSet[sourceArrayIndex.barIndex].data[sourceArrayIndex.dataIndex]
                        && dataSet[changeBarIndex.target]) {
                        
                        var moveData = dataSet[sourceArrayIndex.barIndex].data[sourceArrayIndex.dataIndex]
                        dataSet[sourceArrayIndex.barIndex].data.splice(sourceArrayIndex.dataIndex,1);
                        dataSet[changeBarIndex.target].data.push(moveData);
                    }
                    
                }
            }
            console.log("dataSet is : ----- ", dataSet);

            //更新数据后重新绘制画布
            autoDraw(dataSet)
        }
    }
}

/**
 * 标记函数
*/
function longPress(){
    timeOutEvent = 0;
}

    /**
     * 创建图形
     * */
function createBlock(x,y,){
    // ctx.beginPath();
    // 创建渐变
    // var grd=ctx.createRadialGradient(75,50,5,90,60,100);
    // grd.addColorStop(0,"red");
    // grd.addColorStop(1,"white");

        //判断点击了那个矩形
    changeBarIndex.target=getBarIndex(x,y);

    //更新数据后重新绘制画布
    autoDraw(dataSet);

    console.log(" targetIndex is : ",targetIndex );
}


/**
 * 根据数据绘制堆叠图
*/
function autoDraw(dataSet) {
    
    // 清除画布内容
    ctx.clearRect(0,0,c.width,c.height);

    //绘制坐标
    drawCoordinateSystem();

    for(var j=0;j<dataSet.length;j++){

        //backgroud 绘制条形底块
        ctx.fillStyle="lightGray";
        ctx.fillRect((j+1)*step-bgStep+j*barWidth,0,barWidth+2*bgStep,barHeigh);
    
        var bar = dataSet[j].data;

        var tempHeight = 0;

        //根据数据绘制堆叠图
        for(var i=0;i<bar.length;i++){

        //    console.log("(i+1)%3 == "+(i+1)%3)
                if((i+1)%bar.length==1){
                    //R	
                    ctx.fillStyle="#FF0000";
                }else if((i+1)%bar.length==2){
                    //g
                    ctx.fillStyle="#00ff00";
                }else if((i+1)%bar.length==0){
                    //b
                    ctx.fillStyle="#0000ff";
                }

                //绘制方块
                tempHeight = tempHeight + bar[i].h;
                ctx.fillRect((j+1)*step+j*barWidth,barHeigh-tempHeight ,barWidth,bar[i].h);

                //将对应值写入方块内
                ctx.font = "7px Arial";
                ctx.textAlign = "center";
                ctx.fillStyle = "yellow";
                ctx.fillText(bar[i].h,(j+1)*step+j*barWidth+barWidth/2, barHeigh-tempHeight+bar[i].h/2);

        }
    
    }
     
}


/**
 * 获取目标条块的最大Y轴坐标
*/
function getRectY(a){
    var height = 0;

    var bar=dataSet[a].data
    
    for(var i=0;i<bar.length;i++){
        // console.log("总高 == ",bar[i].h)
        height = height + bar[i].h;
        
    }
    // console.log("---------",height)

    return height
}

/**
 *      获取鼠标选择矩形所在数据索引
*/
function getClickRectIndex(x,y){
    var dataFlag = false;

    for(var i=0;i<dataSet.length;i++){
        var bar = dataSet[i].data;

        var tempHeight=0;
        for(var j=0;j<bar.length;j++){

            var maxY = 0;
            if(j==0){
                maxY = barHeigh;
            }else{
                maxY =barHeigh-tempHeight;
            }

            tempHeight = tempHeight + bar[j].h;

            if(x>=(i+1)*step+i*barWidth&&x<=(i+1)*step+(i+1) *barWidth
            &&
            y>=barHeigh-tempHeight&&y<=maxY){

                    sourceArrayIndex.barIndex = i;
                    sourceArrayIndex.dataIndex = j;
                    newHeigh = bar[j].h;
                    dataFlag = true;
                    changeBarIndex={source:-1,target:-1};
            }
        }
    }

    //选择整块移动
    if(!dataFlag){
        changeBarIndex.source=getBarIndex(x,y)
            
    }
}

/**
 * 获取柱状条索引
 * 
 */
function getBarIndex(x,y){
    for(var i=0;i<dataSet.length;i++){

        if(x>=(i+1)*step-bgStep+i*barWidth&& x <=(i+1)*step+ (i+1)*barWidth+(i+1)*2*bgStep
            &&
            y>=0 && y <= barHeigh){
            console.log('选定了柱状条 ',i)
            return i;
        
        }
    }
    return -1;
}

/**
 * 绘制画布
*/
function drawCanvas(width,height){
    
}

/**
 * 绘制坐标系 Coordinate system
*/
function drawCoordinateSystem(scaleUnitValue){
    //X轴
    ctx.moveTo(0,0)
    ctx.lineTo(0, canvasHeight)
    ctx.lineWidth = 1;
    ctx.strokeStyle="green"
    ctx.stroke()
    
    //y轴
    ctx.moveTo(0,canvasHeight)
    ctx.lineTo(canvasWidth,canvasHeight)
    ctx.stroke()

    for(var i=1;i<5;i++){
        
        // 画纵坐标刻度
        ctx.beginPath();
        ctx.moveTo(0,canvasHeight-i*20);
        ctx.lineTo(canvasWidth, canvasHeight-i*20);
        ctx.lineWidth = 0.1;
        ctx.strokeStyle = "blue";
        ctx.stroke();
        ctx.closePath();
        ctx.font = "7px Arial";
        ctx.textAlign = "left";
        ctx.textBaseline = "top";
        ctx.fillStyle = "green";
        ctx.fillText(i*20,2 , canvasHeight-i*20);
    }

    for(var i=0;i<dataSet.length;i++){

        //定位文字起始坐标
        var x = (i+1)*step+( i+1)*barWidth-barWidth/2;
 
        // 横坐标刻度
        ctx.beginPath();
        ctx.textAlign = "center";
        ctx.textBaseline = "top";
        ctx.font = "7px 黑体";
        ctx.fillStyle = "green";
        ctx.fillText(dataSet[i].barName,x , barHeigh);
    }
}

/**
 * 通过数据值计算单位刻度值
 */
function getScaleUnitValue(dataSet) {
    
}